using System;
using Sce.Pss.Core.Graphics;
using Sce.Pss.Core.Imaging;

namespace Storyteller.Framework.Graphics
{
	public class RenderTexture : Texture
	{
		public RenderTexture(int width, int height)
			: base()
		{
			frameBuffer = new FrameBuffer();
			texture2d = new Texture2D(width, height, false, PixelFormat.Rgba, PixelBufferOption.Renderable);
			frameBuffer.SetColorTarget(texture2d, 0);
			
			graphicsContext = Game.Instance.GraphicsContext;
		}
		
		public void Bind()
		{
			graphicsContext.SetFrameBuffer(frameBuffer);

			viewport = graphicsContext.GetViewport();
			graphicsContext.SetViewport(0, 0, Width, Height);
			
			graphicsContext.SetClearColor(1.0f, 0, 1, 1);
			graphicsContext.Clear(ClearMask.Color);
		}
		
		public void Unbind()
		{
			graphicsContext.SetFrameBuffer(graphicsContext.Screen);
			
			graphicsContext.SetViewport(viewport);
		}

		protected override void Dispose(bool disposing)
		{
			if (!disposed)
			{
				if (disposing)
				{
					// dispose of managed resources
				}

				// dispose of unmanaged resources
				frameBuffer.Dispose();

				disposed = true;
			}

			base.Dispose(disposing);
		}
		
		GraphicsContext graphicsContext;
		FrameBuffer frameBuffer;
		ImageRect viewport;
		
		bool disposed = false;
	}
}
